<?php

class MysqlClass {
	var $db;
	var $db_log;

	function MysqlClass () {
		global $setupdata;
		$this->setupdata=$setupdata;
	}

	function connect_db($HostName, $UserName, $Password, $DBName){
		if (isset($this->setupdata['mysql_connection']) && ($this->setupdata['mysql_connection'] == "pconnect")){
			$this->db=mysql_pconnect($HostName, $UserName, $Password);
		} else  {
			$this->db=mysql_connect($HostName, $UserName, $Password);
		}

		if (isset($this->setupdata['mysql']['connections'])){
			if (!file_exists($this->setupdata['mysql']['connections'])) $h = fopen($this->setupdata['mysql']['connections'], "w");
			else $h = fopen($this->setupdata['mysql']['connections'], "a");
			fwrite($h, time()."\n");
			fclose($h);
		}
		// 1203 == ER_TOO_MANY_USER_CONNECTIONS (mysqld_error.h)
		/*
		if (mysql_errno() == 1203) {
			session_write_close();
			header ("location: index.php?action=error&disc=too_many_users");
			exit();
		}
		*/

		if (!$this->db) {
			$error = mysql_errno().": ".mysql_error();
			$str = "Connect DB";
			$this->mysql_error_send($str, "NULL", "NULL", $error);
			include $this->setupdata['core_dir']."/includes/die.php";
			session_write_close();
			header ("location: index.php?action=error&disc=mysql_connect_db");
			exit();
		}
		if (mysql_select_db($DBName) == FALSE) {
			$error = mysql_errno().": ".mysql_error();
			$str = "Select DB";
			$this->mysql_error_send($str, "NULL", "NULL", $error);
			include $this->setupdata['core_dir']."/includes/die.php";
			session_write_close();
			header ("location: index.php?action=error&disc=mysql_select_db");
			exit();
		}
	}

	function close_db() {
		if (isset($this->db) && (get_resource_type($this->db) == 'mysql link')){
			if (@mysql_close($this->db) == FALSE) {
				$error = mysql_errno().": ".mysql_error();
				$str = "Close DB";
				$this->mysql_error_send($str, "NULL", "NULL", $error);
				include $this->setupdata['core_dir']."/includes/die.php";
				session_write_close();
				header ("location: index.php?action=error&disc=mysql_cloce_db");
				exit();
			}
		}
	}

	function getmicrotime() { 
		list($usec, $sec) = explode(" ", microtime()); 
		return ((float)$usec + (float)$sec); 
	} 
	
	/*
mysql_fetch_array
mysql_num_rows
mysql_insert_id
mysql_fetch_assoc
mysql_fetch_row
mysql_free_result
	*/
	
	function mysql_my_fetch_array($sql, $type=MYSQL_BOTH){
		if (isset($type) && (($type == MYSQL_BOTH) || ($type == MYSQL_ASSOC) || ($type == MYSQL_BOTH))){
		} else $type = MYSQL_BOTH;
		if (is_resource($sql)){
			return mysql_fetch_array($sql, $type);
		} else {
			return FALSE;
		}
	}

	function mysql_my_fetch_assoc($sql){
		if (is_resource($sql)){
			return mysql_fetch_assoc($sql);
		} else {
			return FALSE;
		}
	}

	function mysql_my_fetch_row($sql){
		if (is_resource($sql)){
			return mysql_fetch_row($sql);
		} else {
			return FALSE;
		}
	}
	
	function mysql_my_num_rows($sql){
		if (is_resource($sql)){
			return mysql_num_rows($sql);
		} else {
			return FALSE;
		}
	}

	function mysql_my_insert_id(){
		return mysql_insert_id();
	}

	function mysql_my_free_result($sql){
		if (is_resource($sql)){
			return mysql_free_result($sql);
		} else {
			return FALSE;
		}
	}
	
	function mysql_my_query($str="", $func="", $file=""){
		global $setupdata;
		$tmp = explode(' ', $str, 2);
		$tmp[0] = trim(strtolower($tmp[0]));
		if (isset($setupdata['vars']['tables_not_update']) &&  count($setupdata['vars']['tables_not_update'])>0 && !preg_match("/".join($setupdata['vars']['tables_not_update'],'|')."/", $str)){
			if (($tmp[0] != 'select') && ($tmp[0] != 'set')){
				$sql = mysql_query("SELECT * FROM `".$this->setupdata['table_prefix']."local_vars` WHERE `name`='last_db_update'");
				if ($this->mysql_my_num_rows($sql) == 0) mysql_query("INSERT INTO `".$this->setupdata['table_prefix']."local_vars` ( `id` , `name` , `value` ) VALUES ('', 'last_db_update', '".time()."')");
				else mysql_query("UPDATE `".$this->setupdata['table_prefix']."local_vars` SET `value`='".time()."' WHERE `name` = 'last_db_update'");
			}
		}
		if ($str != "")	{
			if (isset($setupdata['mysql']['log'])){
				$time_start = $this->getmicrotime();
			}
			
			$result = mysql_query($str);
			if ($result) $this->db_log[] = $str;
			if (isset($setupdata['mysql']['log'])){
				$time_end = $this->getmicrotime();
				$time = $time_end - $time_start;
				if (!file_exists($setupdata['mysql']['log'])) $h = fopen($setupdata['mysql']['log'], "w");
				else $h = fopen($setupdata['mysql']['log'], "a");
				fwrite($h, $time." - ".trim($str)." - ".$func." - ".$file."\n");
				fclose($h);
			}
		}
		if (mysql_errno() != "0") {
			$error = mysql_errno().": ".mysql_error();
			while (ob_get_level()) ob_end_clean();
			if (isset($this->setupdata['_debug_'])){
				$message = print_r("<pre>", true);
				$message .= print_r("MYSQL ERROR\n", true);
				$message .= print_r("Mysql query: ".$str."\n", true);
				$message .= print_r("Error code: ".$error."\n", true);
				$message .= print_r("Error in function: ".$func."\n", true);
				$message .= print_r("Error in file: ".$file."\n", true);
				$message .= print_r("</pre>", true);
				print_r($message);
				$this->close_db();
				include $this->setupdata['core_dir']."/includes/die.php";
			}
			$this->mysql_error_send($str, $func, $file, $error);
		} else return $result;
	}

	function mysql_error_send($sql="", $func="", $file="", $error=""){
		global $setupdata;
		$email_to = $setupdata['send_error_to'];
		$headers  = "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
		$headers .= "From: SUPPORT <".$email_to.">\r\n";
		$headers .= "X-Mailer: JustPageIt Mailer 0.1\r\n";
		$subject = "MYSQL ERROR - ".$_SERVER['SERVER_NAME']." - ".$setupdata['base_href'];
		$mess =  "URL  : http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."<br>\r\n";
		if (isset($_SERVER['HTTP_REFERER'])) $mess .=  "URLF : ".$_SERVER['HTTP_REFERER']."<br>\r\n";
		if (isset($_SERVER['REMOTE_ADDR'])) $mess .= print_r("Client IP: ".$_SERVER['REMOTE_ADDR']."<br>\r\n", true);
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $mess .= print_r("Client Proxy: ".$_SERVER['HTTP_X_FORWARDED_FOR']."<br>\r\n", true);
		$mess .= "TPTH : ".$_SERVER["PATH_TRANSLATED"]."<br>\r\n";
		$mess .= "PATH : ".$file."<br>\r\n";
		$mess .= "LINE : ".$func."<br>\r\n";
		$mess .= "SQL  : ".$sql."<br>\r\n";
		$mess .= "ERR  : ".$error."<br>\r\n";
		$mess .= "TIME : ".date("Y.m.d (H:i:s)",time())."<br>\r\n";
		if (isset($_POST) && (count($_POST) > 0)) {
			$mess .= "<br>\r\n";
			$mess .= "POST :<br>\r\n";
			foreach ($_POST as $key=>$value) {
				if (is_array($value)) $mess .= "POST['".$key."'] = ".print_r($value, true)."<br>\r\n";
				$mess .= "POST['".$key."'] = ".$value."<br>\r\n";
			}
		}
		if (isset($_GET) && (count($_GET) > 0)) {
			$mess .= "<br>\r\n";
			$mess .= "GET :<br>\r\n";
			foreach ($_GET as $key=>$value) {
				if (is_array($value)) $mess .= "GET['".$key."'] = ".print_r($value, true)."<br>\r\n";
				else $mess .= "GET['".$key."'] = ".$value."<br>\r\n";
			}
		}
		@mail($email_to, $subject, $mess, $headers);
		if (is_file($this->setupdata['smarty_admin_template_dir']."admin/mysqlerror.tpl"))
			readfile($this->setupdata['smarty_admin_template_dir']."admin/mysqlerror.tpl");
			
		exit();
	}
	
	function mysqlPing()
	{
		if ( !mysql_ping($this->db) ) 
		{
			return 1;
		}
	}
	
	function mysql_reconnect()
	{
		$this->close_db();
		$this->connect_db($this->setupdata['HostName'], $this->setupdata['UserName'], $this->setupdata['Password'], $this->setupdata['DBName']);
	}
}
?>
